<template>
  <div class="container flexRow">
    <div class="conLeft">
      <el-tree
        lazy
        :load="loadNode"
        :data="tree.data"
        :props="tree.defaultProps"
        node-key="id"
        highlight-current
        @node-click="selectNode"
        :current-node-key="orgIdList[0]"
        :default-expanded-keys="orgIdList"
        :expand-on-click-node="false"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span style="padding-top: 8px">
              <!--              <img
                v-if="data.orgType == 0"
                src="../../assets/images/org/logo1.png"
                height="16"
                width="16"
              />-->
              <img
                v-if="data.orgType == 2"
                src="../../assets/images/org/icon_zhongxin.png"
                height="16"
                width="16"
              />
              <img
                v-if="data.orgType == 1"
                src="../../assets/images/org/icon_gongsi2.png"
                height="16"
                width="16"
              />
              <img
                v-if="data.orgType == 3"
                src="../../assets/images/org/icon_bmen5.png"
                height="16"
                width="16"
              />
              <img
                v-if="data.orgType == 4"
                src="../../assets/images/org/icon_xiaozu1.png"
                height="16"
                width="16"
              />
            </span>
            <span style="margin-left: 6px">{{ data.name }}</span>
          </span>
        </template>
      </el-tree>
    </div>
    <div class="conRight">
      <el-form :inline="true" v-model="searchWords" class="search">
        <el-form-item>
          <el-select
            v-model="searchWords.state"
            clearable
            placeholder="状态"
            style="width: 100px"
          >
            <el-option
              v-for="item in stateList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            clearable
            placeholder="姓名/昵称"
            v-model="searchWords.userName"
            style="width: 90px"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            clearable
            placeholder="电话/账号"
            v-model="searchWords.mobile"
            style="width: 130px"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            clearable
            placeholder="常住地址"
            v-model="searchWords.addrDetail"
            style="width: 120px"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            clearable
            placeholder="工作单位"
            v-model="searchWords.enterpriseName"
            style="width: 120px"
          />
        </el-form-item>
        <el-form-item>
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="注册开始时间"
          end-placeholder="注册结束时间"
          value-format="YYYY-MM-DD"
          style="width: 220px"
        />
      </el-form-item>
        <el-form-item>
          <el-button :icon="Search" @click="initList(1, selectTreeData.id)" />
          <el-button type="primary" @click="getAdd">新增</el-button>
        </el-form-item>
      </el-form>
      <div class="table-contain">
        <Table
          height="100%"
          :columns="tableData.columns"
          v-loading="tableData.loading"
          :data="tableData.data"
        >
          <template #state="{ row }">
            <span>
              {{ getTranslate(stateList, "code", row?.state, "name") }}
            </span>
          </template>
          <template #operation="{ row }">
            <el-button
              size="small"
              plain
              :icon="Edit"
              type="warning"
              @click="getEmpower(row)"
            >
              授权
            </el-button>
            <el-button
              size="small"
              plain
              :icon="Edit"
              type="warning"
              @click="resetPassword(row)"
            >
              重置密码
            </el-button>
            <el-button
              size="small"
              plain
              :icon="Edit"
              type="warning"
              @click="getEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              plain
              :icon="Delete"
              type="danger"
              @click="getDel(row)"
            >
              删除
            </el-button>
          </template>
        </Table>
      </div>
      <Page
        :page-data="pageData"
        :total="tableData.total"
        @page-no-change="(pageNum) => (pageData.pageNum = pageNum)"
        @page-size-change="(pageSize) => (pageData.pageSize = pageSize)"
      />
    </div>

    <el-dialog v-model="dialogReset.isOpen" :title="dialogReset.title" width="50%">
      <el-form
        :model="formResetData"
        :label-width="110"
        label-position="top"
        ref="ruleFormResetData"
        :rules="rulesReset"
      >
      <el-row>
          <el-col :span="24">
            <el-form-item :label="'请输入用户「'+formResetData.userName+'」的新密码：'" prop="pwd">
              <el-input v-model.trim="formResetData.pwd"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="footer">
        <el-button
          :loading="btnLoading"
          @click="submitResetForm(ruleFormResetData)"
          class="newBtn"
          type="primary"
        >
          保存
        </el-button>
        <el-button @click="closeTitleReset">取消</el-button>
      </div>
      </el-form>
    </el-dialog>

    <el-dialog v-model="dialog.isOpen" :title="dialog.title" width="50%">
      <el-form
        :inline="true"
        :model="formData"
        :label-width="110"
        ref="ruleFormData"
        :rules="rules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名：" prop="realName">
              <el-input v-model.trim="formData.realName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称：" prop="userName">
              <el-input v-model.trim="formData.userName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话：" prop="mobile">
              <el-input v-model.trim="formData.mobile"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态：" prop="state">
              <el-select
                v-model="formData.state"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in stateList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="组织："
              prop="sysOrgId"
              :class="formData.name ? 'cascader-color' : ''"
            >
              <el-cascader
                :placeholder="formData.name || '请选择'"
                v-model="formData.sysOrgId"
                :props="sysOrgProps"
                :show-all-levels="false"
                @change="changeOrg"
                ref="classifyRef"
              />
            </el-form-item>
          </el-col>
         
        </el-row>
      </el-form>
      <div class="footer">
        <el-button
          :loading="btnLoading"
          @click="submitForm(ruleFormData)"
          class="newBtn"
          type="primary"
        >
          保存
        </el-button>
        <el-button @click="closeTitle">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      v-model="dialogTree.isOpen"
      :title="dialogTree.title"
      width="50%"
    >
      <el-tree
        v-if="dialogTree.isOpen"
        ref="treeRef"
        style="min-height: 300px"
        :data="treeData"
        show-checkbox
        node-key="id"
        :default-checked-keys="defaultCheckedKeys"
        :props="defaultProps"
      >
      </el-tree>
      <div class="footer">
        <el-button
          class="newBtn"
          type="primary"
          @click="submitTree()"
          :loading="btnLoading"
          >保存</el-button
        >
        <el-button @click="closeTitleTree()">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from "vue";
import Table from "@/components/pageTable/table.ts";
import { getTranslate } from "@/util/index.ts";
import { ElMessage, ElMessageBox } from "element-plus";
import Page from "@/components/pageTable/Page.vue";
import md5 from "js-md5";
import { baseURL } from "@/util/request";
import type { CascaderProps } from "element-plus";
import {
  authUserRole,
  delSysUser,
  pageSysUser,
  resetPwd,
  saveSysUser,
  selectOrgChilds,
  selectPositionByName,
  selectRoleIdListByUserId,
  selectSysRoleList,
  selectUserById,
  syncUser,
  updateSysUser,
} from "@/api/user.ts";
import { Delete, Edit, Search } from "@element-plus/icons-vue";
import Node from "element-plus/es/components/tree/src/model/node";
import { position } from "html2canvas/dist/types/css/property-descriptors/position";

const syncButtonLoading = ref<boolean>(false);
  const date = ref<string[]>();
let dialog = reactive({
  isOpen: false,
  title: "",
});
let dialogTree = reactive({
  isOpen: false,
  title: "",
});
let dialogReset = reactive({
  isOpen: false,
  title: "",
});
let defaultProps = {
  children: "children",
  label: "roleName",
};
const classifyRef = ref();
const selectTreeData = ref();
const treeData = ref();
const currentObj = ref();
const btnLoading = ref<boolean>(false);
const orgIdList = ref<any[]>([]);
const treeRef = ref();
const stateList = ref<any[]>([
  { code: "1", name: "启用" },
  { code: "2", name: "禁用" },
]);
const positionList = ref<any[]>([]);
const defaultCheckedKeys = ref<any[]>([]);
const tree = reactive({
  loading: true,
  defaultProps: {
    children: "children",
    label: "name",
  },
  data: [],
});
const checkPhone = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback("请输入");
    return;
  }
  if (value && !isMobile(value)) {
    callback("请输入正确的手机号！");
    return;
  } else {
    callback();
  }
};
const tableData = reactive({
  columns: [
    { prop: "state", label: "状态", width: 60, template: true },
    { prop: "userName", label: "昵称", width: 110 },
    { prop: "realName", label: "姓名", width: 110 },
    { prop: "name", label: "组织", width: 160 },
    
    { prop: "mobile", label: "电话/账号", width: 120 },
    { prop: "addrDetail", label: "地址", width: 180 },
    { prop: "enterpriseName", label: "工作单位", width: 225 },
    {
      prop: "operation",
      label: "操作",
      fixed: "right",
      template: true,
      width: 400,
    },
  ],
  loading: true,
  total: 0,
  data: [],
});
const ruleFormData = ref();
const rules = reactive({
  userName: [{ required: true, message: "请输入", trigger: "blur" }],
  realName: [{ required: true, message: "请输入", trigger: "blur" }],
  
  mobile: [{ required: true, validator: checkPhone, trigger: "blur" }],
  userType: [{ required: true, message: "请选择", trigger: "change" }],
  sysOrgId: [{ required: true, message: "请选择", trigger: "change" }],
  state: [{ required: true, message: "请选择", trigger: "change" }],
});

const ruleFormResetData = ref();
const rulesReset = reactive({
  pwd: [{ required: true, message: "请输入", trigger: "blur" }],
});

const pageData = reactive({
  pageSize: 15,
  pageNum: 1,
});

let searchWords = reactive({
  state: "",
  userName: "",
  mobile: "",
  startTime:"",
  endTime:"",
  addrDetail: "",
  enterpriseName: "",
});

let formData = reactive<any>({
  id: "",
  name: "",
  mobile: "",
  state: "",
  sort: "99",
  sysOrgId: "",
  userName: "",
  userType: "1",
});
let formResetData = reactive<any>({
  id: "",
  name:"",
  pwd: "",
});
 
const sysOrgProps: CascaderProps = {
  lazy: true,
  value: "id",
  label: "name",
  checkStrictly: true,
  emitPath: false,
  lazyLoad: async (node, resolve) => {
    const { data } = await selectOrgChilds({
      parentId: node?.data?.id || 0,
      state: 1,
    });
    resolve(data);
  },
};
function changeOrg(val: any) {
  formData.sysOrgId = val;
  classifyRef.value.togglePopperVisible();
}
//列表分页查询
async function initList(page: number, sysOrgId: string = "") {
  console.log(sysOrgId)
  pageData.pageNum = page || 1;
  let params = {
    pageNum: page || 1,
    pageSize: pageData.pageSize,
    sysOrgId: sysOrgId || "1",
    ...searchWords,
  };
  tableData.loading = true;
  const { data, msg, success } = await pageSysUser(params);
  if (!success) {
    ElMessage.error(msg);
    tableData.loading = false;
    return;
  }
  tableData.loading = false;
  tableData.data = data?.list;
  tableData.total = data?.total;
}

//保存
async function submitForm(ruleFormData: any) {
  if (!ruleFormData) return;
  await ruleFormData.validate(async (valid: any, fields: any) => {
    if (valid) {
      btnLoading.value = true;
      let api = !formData.id || formData.id == "" ? saveSysUser : updateSysUser;
      const { msg, success } = await api(formData);
      if (!success) {
        ElMessage.error(msg);
        btnLoading.value = false;
        return;
      }
      ElMessage.success("操作成功");
      await initList(pageData.pageNum, selectTreeData.value.id);
      btnLoading.value = false;
      dialog.isOpen = false;
    } else {
      console.log("error submit!", fields);
    }
  });
}
//新增
function getAdd() {
  dialog.isOpen = true;
  dialog.title = "新增用户";
  Object.keys(formData).forEach((key) => (formData[key] = null));
  formData.sort = "99";
  formData.userType = "1";
}
//编辑
async function getEdit(row: any) {
  const { data, msg, success } = await selectUserById({ userId: row.id });
  if (!success) {
    ElMessage.error(msg);
    return;
  }
  if (data) {
    data.state = data.state?.toString();
  }

  Object.assign(formData, { ...data, userType: data.userType.toString() });
  dialog.isOpen = true;
  dialog.title = "编辑用户";
}
//删除
function getDel(row: any) {
  ElMessageBox.confirm(`是否删除?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { msg, success } = await delSysUser({ userId: row.id });
    if (!success) {
      ElMessage.error(msg);
      return;
    }
    ElMessage.success("操作成功");
    await initList(pageData.pageNum, selectTreeData.value.id);
  });
}
async function resetPassword(row: any) {

  // const { data, msg, success } = await selectUserById({ userId: row.id });
  // if (!success) {
  //   ElMessage.error(msg);
  //   return;
  // }
  // if (data) {
  //   data.state = data.state?.toString();
  // }

  // Object.assign(formData, { ...data, userType: data.userType.toString() });
  formResetData.userName = row.userName
  formResetData.id = row.id
  dialogReset.isOpen = true;
  dialogReset.title = "重置密码";

  return;


  ElMessageBox.confirm(`是否确认重置?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { msg, success } = await resetPwd({ userId: row.id });
    if (!success) {
      ElMessage.error(msg);
      return;
    }
    ElMessage.success("操作成功");
    await initList(pageData.pageNum, selectTreeData.value.id);
  });
}

//保存
async function submitResetForm(ruleFormData: any) {
  if (!ruleFormData) return;
  await ruleFormData.validate(async (valid: any, fields: any) => {
    if (valid) {
      btnLoading.value = true;
      let api = !formData.id || formData.id == "" ? saveSysUser : updateSysUser;
      const { msg, success } = await resetPwd({ userId: formResetData.id,pwd: md5(formResetData.pwd)});
      if (!success) {
        ElMessage.error(msg);
        btnLoading.value = false;
        return;
      }
      ElMessage.success("操作成功");
      await initList(pageData.pageNum, selectTreeData.value.id);
      btnLoading.value = false;
      dialogReset.isOpen = false;
    } else {
      console.log("error submit!", fields);
    }
  });
}


async function selectNode(data: any) {
  selectTreeData.value = data;
  await initList(1, data.id);
}
async function getEmpower(row: any) {
  currentObj.value = row;
  await getSelectRoleIdListByUserId(row.id);
}
//获取当前用户角色
async function getSelectRoleIdListByUserId(id: any) {
  const { data = [], msg, success } = await selectRoleIdListByUserId(id);
  if (!success) {
    ElMessage.error(msg);
    return;
  }
  defaultCheckedKeys.value = data;
  await getTreeData();
}
async function getTreeData() {
  const { data = [], msg, success } = await selectSysRoleList();
  if (!success) {
    ElMessage.error(msg);
    return;
  }
  treeData.value = data;
  dialogTree.title = "授权";
  dialogTree.isOpen = true;
}

async function submitTree() {
  console.log(treeRef.value.getCheckedKeys());
  let menuList = treeRef.value.getCheckedKeys();
  const { msg, success } = await authUserRole({
    sysRoleIds: menuList,
    sysUserId: currentObj.value.id,
  });
  if (!success) {
    ElMessage.error(msg);
    return;
  }
  closeTitleTree();
}
async function getPosition() {
  const { data, msg, success } = await selectPositionByName();
  if (!success) {
    ElMessage.error(msg);
    return;
  }
  positionList.value = data;
}

async function loadNode(node: Node, resolve: (data: any[]) => void) {
  tree.loading = true;
  const { data, msg, success } = await selectOrgChilds({
    parentId: node?.level ? node?.data?.id : 0,
    state: 1,
  });
  tree.loading = false;
  if (!success) {
    ElMessage.error(msg);
    return resolve([]);
  }
  if (node?.level == 0) {
    selectTreeData.value = data;
    await initList(1, data[0].id);
  }
  if (!node?.level && data.length > 0) {
    orgIdList.value.push(data[0].id);
  }
  return resolve(data || []);
}
function isMobile(val: any) {
  return /^1[3-9]\d{9}$/.test(val);
}
function closeTitle() {
  Object.keys(formData).forEach((key) => (formData[key] = null));
  dialog.isOpen = false;
}

function closeTitleReset() {
  Object.keys(formResetData).forEach((key) => (formResetData[key] = null));
  dialogReset.isOpen = false;
}

function closeTitleTree() {
  dialogTree.isOpen = false;
  dialogTree.title = "";
}

onMounted(async () => {
  await getPosition();
});

watch(pageData, async () => {
  await initList(pageData.pageNum, selectTreeData.value.id);
});
watch(searchWords, async () => {
  // console.log(selectTreeData.value.id)
  await initList(1, selectTreeData.value.id);
});

watch(date, (value) => {
  searchWords.startTime = value?.[0] ? `${value?.[0]}` : "";
  searchWords.endTime = value?.[1] ? `${value?.[1]}` : "";
});
</script>

<style scoped lang="scss">
@import "@/assets/styles/common";
.conLeft {
  width: 250px;
}
.conRight {
  width: calc(100% - 268px);
}
.table-contain {
  width: 100%;
  height: calc($router-component-contain-height - 80px);
}
.el-dialog {
  .el-form-item {
    width: 90%;
    .el-select {
      width: 100%;
    }
  }
  .footer {
    width: 100%;
    text-align: center;
    margin-top: 50px;
  }
}
:deep(.el-table__cell) {
  position: unset;
}
:deep(.el-image-viewer__canvas) {
  width: 60%;
  margin-left: 20%;
}
.cascader-color {
  :deep(.el-input__inner::placeholder) {
    color: var(--el-input-text-color, var(--el-text-color-regular));
  }
}
</style>
